<?php

namespace app\api\controller;

use app\api\model\ConfigSystem as Config;
use app\api\model\Dymanic;
use app\api\model\UserClaimAddress;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords;
use think\Db;
use think\Validate;

class Address extends Common {
    /**
     * @param $name
     * @param $address
     * @param $longitude
     * @param $latitude
     * @param $image_1
     * @param $image_2
     * @param $image_3
     * @return mixed
     */
    public function claim($id = '', $name = '', $address = '', $longitude = '', $latitude = '', $image_1 = '', $image_2 = '', $image_3 = '', $contact = '', $open_time = '', $city = '') {
        $rule = [
            'user_id'   => 'require',
            'name'      => 'require|max:40',
            'address'   => 'require|max:60',
            'longitude' => 'require|between:0.01,180',
            'latitude'  => 'require|between:0.01,180',
            'image_1'   => 'require',
            'image_2'   => 'require',
            'image_3'   => 'require',
            'contact'   => 'max:20',
            'open_time' => 'max:200',
        ];

        $msg = [
            'user_id.require'   => '未登录',
            'name.require'      => '地址名称必填',
            'name.max'          => '地址名称最多不能超过40个字符',
            'address.require'   => '详细地址必须填写',
            'address.max'       => '详细地址最多不能超过60个字符',
            'longitude.require' => '经纬度错误',
            'longitude.between' => '经纬度错误',
            'latitude.require'  => '经纬度错误',
            'latitude.between'  => '经纬度错误',
            'image_1.require'   => '图片未上传',
            'image_2.require'   => '图片未上传',
            'image_3.require'   => '图片未上传',
            'contact.max'       => '联系方式错误',
            'open_time.max'     => '营业时间错误',
        ];
        $data = [
            'user_id'   => $this->member['id'],
            'name'      => $name,
            'address'   => $address,
            'longitude' => $longitude,
            'latitude'  => $latitude,
            'image_1'   => $image_1,
            'image_2'   => $image_2,
            'image_3'   => $image_3,
            'contact'   => $contact,
            'open_time' => $open_time,
            'city'      => $city,
            'state'     => 0,
        ];

        $validate = new Validate($rule, $msg);
        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        }
        $method = '创建';
        if ($id) {
            $method = '修改';
            $col    = Db::name('user_claim_address')->where(['id' => $id, 'user_id' => $this->member['id']])->find();
            if (!$col) {
                return $this->miss('申领信息失效');
            }
            if ($col['state'] != -1) {
                return $this->miss('当前状态无法修改');
            }
            $data['update_time'] = time();
            $res                 = Db::name('user_claim_address')->where(['id' => $id])->update($data);
        } else {
            $address_id  = UserClaimAddress::FindByCreate(['name' => $name, 'address' => $address, 'longitude' => $longitude, 'latitude' => $latitude, 'city' => $city]);
            $addressInfo = Db::name('user_claim_address')->where(['id' => $address_id])->find();
            if ($addressInfo['user_id'] && in_array($addressInfo['state'], [0, 1])) {
                return $this->miss('当前地址已被认领');
            }
            $res        = Db::name('user_claim_address')->where(['id' => $address_id])->update($data);
            $data['id'] = $address_id;
        }
        if ($res) {
            return $this->pass($method . '成功', 'data', $data);
        }
        return $this->miss($method . '失败');
    }

    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function myadd($page = 1, $pagesize = 20) {
        $data = Db::name('user_claim_address')
            ->where(['user_id' => $this->member['id']])
            ->field('id,name,address,longitude,latitude,image_3 as image,state,reason,city')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('id desc')
            ->select();
        return $this->pass($data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function info($id) {
        $data = Db::name('user_claim_address')
            ->where(['id' => $id])
            ->find();
        if (!$data) {
            return $this->miss('地址未找到');
        }
        if ($this->member['id'] != $data['user_id']) {
            if ($data['state'] != 1) {
                return $this->miss('地址未找到');
            }
            unset($data['image_1']);
        }

        $data['is_collect'] = Db::name('user_collect_address')->where(['user_id' => $this->member['id'], 'address_id' => $id])->count();

        $data['goods']      = action('api/addressgoods/get', ['address_id' => $id, 'page' => 1, 'pagesize' => 2, 'where' => ['state' => 1, 'status' => 1]]);
        $data['sign_heads'] = Db::name('flags')->where(['address_id' => $id])->group('user_id')->limit(10)->column('user_id');
        if (sizeof($data['sign_heads'])) {
            $data['sign_heads'] = Db::name('user')->where(['id' => ['in', $data['sign_heads']]])->column('head_100');
        }

        $data['redpackets'] = Db::name('user_address_red_packet')->where(['status' => 0, 'paystate' => 1, 'stock' => ['>', 0], 'address_id' => $id])->field('type,price,value')->select();

        $data['sign_today'] = Db::name('flags')->where(['address_id' => $id])->whereTime('create_time', 'today')->cache(60)->count();
        $data['sign_week']  = Db::name('flags')->where(['address_id' => $id])->whereTime('create_time', 'week')->cache(60)->count();

        $data['open_time_desc'] = '';
        $day                    = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        $open_time              = $data['open_time'];
        if ($open_time) {
            $open_time    = explode('|', $open_time);
            $open_time[0] = explode(',', $open_time[0]);
            $daylen       = sizeof($open_time[0]);
            $open_times   = [];
            if ($daylen > 1) {
                $next         = 1;
                $index        = 0;
                $open_times[] = [$day[0]];
                while ($next) {
                    if ($open_time[0][$next - 1] == $open_time[0][$next] - 1) {
                        $open_times[$index][1] = $day[$open_time[0][$next] - 1];
                        if (isset($open_time[0][$next + 1])) {
                            $next++;
                        } else {
                            $next = 0;
                        }
                    } else {
                        $index++;
                        $open_times[$index][0] = $day[$open_time[0][$next] - 1];
                        if (isset($open_time[0][$next + 1])) {
                            $next++;
                        } else {
                            $next = 0;
                        }
                    }
                }
                foreach ($open_times as $key => $value) {
                    $open_times[$key] = implode('至', $open_times[$key]);
                }
            } else {
                foreach ($open_time[0] as $key => $value) {
                    $open_times[] = $day[$value - 1];
                }
            }
            $data['open_time_desc'] = implode(',', $open_times) . ' ' . $open_time[1];
        }
        return $this->pass($data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function dele($id = '') {
        $res = Db::name('user_claim_address')->where(['id' => $id, 'user_id' => $this->member['id']])->update(['user_id' => 0]);
        if ($res) {
            return $this->pass('删除成功');
        }
        return $this->miss('删除失败');
    }

    /**
     * @param $address_id
     * @param $image
     * @param $name
     * @param $contact
     * @return mixed
     */
    public function edit($id, $image, $name, $contact) {
        $res = Db::name('user_claim_address')
            ->where(['id' => $id, 'user_id' => $this->member['id']])
            ->update([
                'image_3' => $image,
                'name'    => $name,
                'contact' => $contact,
            ]);
        if ($res) {
            return $this->pass('修改成功');
        }
        return $this->miss('修改失败');
    }

    /**
     * @param $address_id
     * @param $type
     * @param $price
     * @param $num
     * @param $paymethod
     * @param $expire_time
     * @param $h5
     * @return mixed
     */
    public function sendredpacket($address_id = '', $type = 1, $price = 1, $num = 1, $paymethod = 2, $expire_time = '', $h5 = 0, $w2 = 0) {
        $today   = date('Y-m-d H:i');
        $timenow = time();
        $rule    = [
            'user_id'     => 'require',
            'address_id'  => 'require',
            'type'        => 'require|in:1,2,3',
            'price'       => 'require|between:0.01,99',
            'num'         => 'require|between:1,999',
            'paymethod'   => 'require|in:' . ($type && $type == 1 ? '2,3' : '0,1'),
            'expire_time' => 'require|after:' . $today,
        ];

        $msg = [
            'user_id.require'     => '未登录',
            'address_id.require'  => '地址选择错误',
            'type.require'        => '类型错误',
            'type.in'             => '类型错误',
            'price.require'       => '金额必须填写',
            'price.between'       => '金额填写错误',
            'num.require'         => '个数必须填写',
            'num.between'         => '个数填写错误',
            'paymethod.require'   => '支付方式选择错误',
            'paymethod.in'        => '支付方式选择错误',
            'expire_time.require' => '有效期错误',
            'expire_time.after'   => '有效期错误',
        ];
        $data = [
            'user_id'     => $this->member['id'],
            'address_id'  => $address_id,
            'type'        => $type,
            'price'       => $price,
            'num'         => $num,
            'paymethod'   => $paymethod,
            'number'      => 'rd' . uniqid(),
            'expire_time' => $expire_time,
            'create_time' => $timenow,
            'update_time' => $timenow,
        ];

        $validate = new Validate($rule, $msg);
        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        }
        $addressInfo = Db::name('user_claim_address')->where(['id' => $address_id, 'user_id' => $this->member['id']])->find();
        if ($addressInfo) {
            if ($addressInfo['state'] != 1) {
                return $this->miss('地址还未通过审核');
            }
        } else {
            return $this->miss('地址不存在');
        }
        $data['expire_time'] = strtotime($data['expire_time']);
        $data['totalprice']  = round($data['price'] * $data['num'], 2);
        $data['totalvalue']  = $type == 1 ? $data['totalprice'] * 5 : $data['totalprice'];
        $data['stock']       = $data['num'];
        $data['id']          = Db::name('user_address_red_packet')->insertGetId($data);
        if (!$data['id']) {
            return $this->miss('创建失败');
        }
        switch ((int) $type) {
        case 1:
            $actions = ['api/Alipay/tradeAppPay', 'api/Wechat/app'];
            if ($h5) {
                return $this->pass('创建成功', 'data', ['order_sn' => $data['number'], 'url' => 'api/wap/pay']);
            } else {
                $methods = $actions[$paymethod - 2];
                if ($w && $methods=='api/Wechat/app'){
                    $methods = 'api/Wechat2/app';
                }
                $data['url'] = action($methods, ['order_sn' => $data['number'], 'total_amount' => $data['totalprice'], 'returnJson' => false]);
            }
            break;
        case 2:
            $paystate = Balance::index($this->member['id'], $data['totalprice'], '发放红包 no.' . $data['number']);
            if ($paystate) {
                Db::name('user_address_red_packet')->where(['id' => $data['id']])->update(['paystate' => 1, 'pay_time' => $timenow]);
            } else {
                Db::name('user_address_red_packet')->delete($data['id']);
                return $this->miss('金币不足');
            }
            break;
        case 3:
            $paystate = YaoqingRecords::index($this->member['id'], 0, $data['totalprice'], '发放红包 no.' . $data['number'], 1, '', 1);
            if ($paystate) {
                Db::name('user_address_red_packet')->where(['id' => $data['id']])->update(['paystate' => 1, 'pay_time' => $timenow]);
            } else {
                Db::name('user_address_red_packet')->delete($data['id']);
                return $this->miss('积分不足');
            }
            break;
        }
        return $this->pass($data);
    }

    /**
     * @param $address_id
     * @return mixed
     */
    public function redpackets($address_id) {
        $data = Db::name('user_address_red_packet')
            ->where(['address_id' => $address_id, 'paystate' => 1, 'stock' => ['<>', 0], 'status' => 0])
            ->order('id desc')
            ->field('id,type,price,totalprice,num,stock,status,expire_time')
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['expire_time'] = date('Y-m-d H:i:s', $value['expire_time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $packet_id
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function redpacketRecords($packet_id, $page = 1, $pagesize = 20) {
        $data = Db::name('user_address_redpacket_records')
            ->where(['address_redpacket_id' => $packet_id])
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->field('address_redpacket_id,data', 'filter')
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['user'] = _user_cache($value['user_id']);
            $data[$key]['time'] = date('Y-m-d H:i:s', $value['time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $name
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function search($name, $page = 1, $pagesize = 20) {
        $data = Db::name('user_claim_address')
            ->where(['name' => ['like', '%' . $name . '%'], 'state' => 1])
            ->field('id,name,address,longitude,latitude,city,image_3 image,collect')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        $packets      = Db::name('user_address_red_packet')->where(['status' => 0, 'paystate' => 1, 'stock' => ['>', 0], 'address_id' => ['in', array_column($data, 'id')]])->cache(60)->field('address_id,type,price,value')->select();
        $packetsGroup = [];
        foreach ($packets as $key => $value) {
            if (!isset($packetsGroup[$value['address_id']])) {
                $packetsGroup[$value['address_id']] = [];
            }
            $packetsGroup[$value['address_id']][] = $value;
        }
        foreach ($data as $key => $value) {
            $data[$key]['sign_today'] = Db::name('flags')->where(['address_id' => $value['id']])->whereTime('create_time', 'today')->cache(60)->count();
            $data[$key]['sign_week']  = Db::name('flags')->where(['address_id' => $value['id']])->whereTime('create_time', 'week')->cache(60)->count();
            $data[$key]['redpackets'] = $packetsGroup[$value['id']] ?? [];
        }
        return $this->pass($data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function collect($id) {
        $has = Db::name('user_collect_address')->where(['user_id' => $this->member['id'], 'address_id' => $id])->find();
        if ($has) {
            $res = Db::name('user_collect_address')->delete($has['id']);
            if ($res) {
                Db::name('user_claim_address')->where(['id' => $id])->setDec('collect');
                return $this->pass('操作成功');
            }
        } else {
            $res = Db::name('user_collect_address')->insert(['user_id' => $this->member['id'], 'address_id' => $id, 'time' => time()]);
            if ($res) {
                Db::name('user_claim_address')->where(['id' => $id])->setInc('collect');
                return $this->pass('操作成功');
            }
        }
        return $this->miss('操作失败');
    }

    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function collects($page = 1, $pagesize = 20) {
        $data = Db::name('user_collect_address')
            ->alias('a')
            ->join('user_claim_address b', 'a.address_id=b.id')
            ->where(['a.user_id' => $this->member['id']])
            ->field('a.address_id,b.name,b.address,b.image_3 image,b.sign,b.collect')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('a.id desc')
            ->select();
        return $this->pass($data);
    }

    /**
     * @param $longitude
     * @param $latitude
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function nearby($longitude, $latitude, $page = 1, $pagesize = 20) {
        $data = Db::name('user_claim_address')
            ->where(['state' => 1])
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->field('id,name,address,city,round(6378.138*2*asin(sqrt(pow(sin( (36.668530*pi()/180-latitude*pi()/180)/2),2)+cos(36.668530*pi()/180)*cos(latitude*pi()/180)* pow(sin( (117.020359*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance')
            ->order('distance asc')
            ->select();
        return $this->pass($data);
    }

    /**
     * @param $address_name
     * @param $address_desc
     * @param $longitude
     * @param $latitude
     * @param $content
     * @param $images
     * @param $video
     * @return mixed
     */
    public function realtimesign($address_name = '', $address_desc = '', $longitude = '', $latitude = '', $content = '', $images = '', $video = '', $public = 1) {
        $timenow     = time();
        $mylongitude = $this->member['longitude'];
        $mylatitude  = $this->member['latitude'];
        $city        = $this->member['city'];
        $user_id     = $this->member['id'];
        $prev        = Db::name('flags')->where(['user_id' => $user_id, 'cate' => 2, 'day' => 1])->order('id desc')->find();
        $config      = Config::index('address_sign');
        if ($prev) {
            $distance = _distance($prev['longitude'], $prev['latitude'], $longitude, $latitude, 1);
            if ($distance > $config['address_sign_prev_distance']) {
                $prev = false;
            }
        }
        $distance = _distance($mylongitude, $mylatitude, $longitude, $latitude, 1);
        $enroll = $video && !getenv('APP_OSS_VIDEO_UPLOAD') ? 1 : 0;
        $data     = [
            'user_id'     => $user_id,
            'city'        => $city,
            'longitude'   => $longitude,
            'latitude'    => $latitude,
            'address'     => $address_name,
            'day'         => $distance < $config['address_sign_distance'] && !$prev ? 1 : 0,
            'content'     => $content,
            'create_time' => $timenow,
            'update_time' => $timenow,
            'cate'        => 2,
            'type'        => $video ? 2 : 1,
            'images'      => $images,
            'video'       => $enroll ? ($video?'http://'.getenv('APP_URL').$video:$video) : $video,
        ];
        $data['address_id'] = UserClaimAddress::FindByCreate(['name' => $address_name, 'address' => $address_desc, 'longitude' => $longitude, 'latitude' => $latitude, 'city' => $city]);
        $result             = Db::name('flags')->insertGetId($data);
        if (!$result) {
            return $this->miss('打卡失败,请重试');
        }
        if ($public) {
            $dyinfo = Dymanic::add([
                'userid'      => $data['user_id'],
                'content'     => $data['content'],
                'video'       => $video,
                'sumbImage'   => $video ? '' : $data['images'],
                'masterimg'   => $video ? '' : $data['images'],
                'cover'       => $video ? $data['images'] : '',
                'citys'       => $data['city'],
                'source_type' => 2,
                'source_id'   => $result,
                'enroll'      => $enroll,
            ]);
            if ($dyinfo && $enroll) {
                _rabbitMqPublish('ffmpeg', [
                    'id' => $dyinfo['dy_id']
                ]);
            }
        }

        $value = 0;
        if ($data['address_id']) {
            if ($distance < $config['address_sign_distance'] && !$prev) {
                $todaysign  = Db::name('flags')->where(['user_id' => $user_id, 'cate' => 2, 'day' => 1])->whereTime('create_time', 'today')->count();
                $configSign = Db::name('config_of_address_sign')->where(['num' => $todaysign])->find();
                if ($configSign) {
                    $value = mt_rand($configSign['min'], $configSign['max']);
                    if ($value) {
                        Balance::index($user_id, $value, '实时打卡获得金币', 1);
                    }
                }
            }
            if ($distance < $config['address_sign_distance']) {
                Db::name('user_claim_address')->where(['id' => $data['address_id']])->setInc('sign');
                UserClaimAddress::sendredpacket($data['address_id'], $data['user_id'], 1, $result);
            }
        }
        return $this->pass('打卡成功', 'data', ['value' => $value]);
    }

    /**
     * @param $longitude
     * @param $latitude
     * @return mixed
     */
    public function checksign($longitude, $latitude) {
        $mylongitude = $this->member['longitude'];
        $mylatitude  = $this->member['latitude'];
        $user_id     = $this->member['id'];
        $prev        = Db::name('flags')->where(['user_id' => $user_id, 'cate' => 2, 'day' => 1])->order('id desc')->find();
        $return      = 0;
        $value       = '';

        $config = Config::index('address_sign');
        if ($prev) {
            $distance = _distance($prev['longitude'], $prev['latitude'], $longitude, $latitude, 1);
            if ($distance < $config['address_sign_prev_distance']) {
                $return = 1;
            }
        }
        $distance         = _distance($mylongitude, $mylatitude, $longitude, $latitude, 1);
        $dontOverDistence = $distance < $config['address_sign_distance'];
        if ($return == 0) {
            if ($dontOverDistence) {
                $todaysign  = Db::name('flags')->where(['user_id' => $user_id, 'cate' => 2, 'day' => 1])->whereTime('create_time', 'today')->count();
                $configSign = Db::name('config_of_address_sign')->where(['num' => $todaysign + 1])->find();
                if ($configSign) {
                    $value = $configSign['min'] == $configSign['max'] ? $configSign['max'] : $configSign['min'] . '-' . $configSign['max'];
                } else {
                }
            } else {
                $return = 2;
            }
        }
        if (!isset($configSign)) {
            $configSign = ['min' => 0, 'max' => 0];
        }
        $addressPacketsText = '';
        $address_id         = $dontOverDistence ? UserClaimAddress::FindByArea($longitude, $latitude) : 0;
        if ($address_id) {
            $addressPackets     = UserClaimAddress::getredpacket($address_id, $user_id);
            $addressPacketsText = [];
            foreach ($addressPackets as $key => $money) {
                if ($key == 'volley' && ($money > 0 || $value)) {
                    $addressPacketsText[] = $configSign['min'] == $configSign['max'] ? ($configSign['max'] + $money) . ' 金币' : ($configSign['min'] + $money) . '-' . ($configSign['max'] + $money) . ' 金币';
                } elseif ($key == 'score' && $money > 0) {
                    $addressPacketsText[] = $money . ' 积分';
                } elseif ($key == 'coupon' && $money > 0) {
                    $addressPacketsText[] = $money . ' 元优惠券';
                }
            }
            $addressPacketsText = $addressPacketsText ? '当前位置打卡预计可获得 ' . implode('、', $addressPacketsText) : '';
        } else {
            $addressPacketsText = $value ? '当前位置打卡预计可获得 ' . $value . ' 金币' : '';
        }
        switch ($return) {
        case 1:
            return $this->pass($addressPacketsText ? $addressPacketsText : '当前位置距上次打卡位置较近，无金币奖励');
            break;
        case 2:
            return $this->pass($addressPacketsText ? $addressPacketsText : '距离打卡位置较远，无金币奖励');
            break;

        default:
            return $this->pass($addressPacketsText ? $addressPacketsText : '今日打卡得金币已达上限');
            break;
        }
    }

    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function signtrack($page = 1, $pagesize = 50, $mindate = '', $maxdate = '') {
        $where = ['user_id' => $this->member['id'], 'delete_time' => 0, 'address' => ['<>', '']];
        if ($mindate) {
            if ($maxdate) {
                $where['create_time'] = ['between', [strtotime($mindate), strtotime($maxdate)]];
            } else {
                $where['create_time'] = ['>=', strtotime($mindate)];
            }
        } elseif ($maxdate) {
            $where['create_time'] = ['<=', strtotime($maxdate)];
        }
        $data = Db::name('flags')
            ->where($where)
            ->order('id desc')
            ->field('id,address,images,video,create_time')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        $list       = [];
        $redpacket  = Db::name('user_address_redpacket_records')->where(['user_id' => $this->member['id'], 'source_type' => 1, 'source_id' => ['in', array_column($data, 'id')]])->field('type,price,source_id')->select();
        $redpackets = [];
        foreach ($redpacket as $key => $value) {
            if (!isset($redpackets[$value['source_id']])) {
                $redpackets[$value['source_id']] = [];
            }
            $redpackets[$value['source_id']][] = $value;
        }
        foreach ($data as $key => $value) {
            $time          = date('Y-m-d', $value['create_time']);
            $value['time'] = date('H:i', $value['create_time']);
            unset($value['create_time']);
            $value['redpackets'] = $redpackets[$value['id']] ?? false;
            $list[$time][]       = $value;
        }
        return $this->pass($list);
    }

    /**
     * @param $address_id
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function signrecords($address_id, $page = 1, $pagesize = 20) {
        $myuid               = $this->member['id'];
        $where               = ['delete_time' => 0, 'private' => 0];
        $where['address_id'] = $address_id;
        $data                = Db::name('flags')
            ->where($where)
            ->order('id desc')
            ->field('private,longitude,latitude,update_time,delete_time,address_id,address,city', 'filter')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        $likes = Db::name('flag_likes')->where(['user_id' => $myuid, 'flags_id' => ['in', array_column($data, 'id')]])->column('flags_id');
        foreach ($data as $key => $value) {
            $data[$key]['images']      = $value['images'] ? explode(',', $value['images']) : [];
            $data[$key]['is_like']     = in_array($value['id'], $likes);
            $data[$key]['user']        = _user_cache($value['user_id']);
            $data[$key]['create_time'] = _time($value['create_time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $page
     * @param $pagesize
     * @param $city
     * @param $desc
     * @param $flagcate
     * @param $keyword
     * @return mixed
     */
    public function hot($page = 1, $pagesize = 20, $city = '', $desc = 0, $flagcate = 0, $keyword = '') {
        $page = intval($page);
        $page = $page ? $page : 1;
        $data  = [];
        $where = ['state' => 1];
        if ($city) {
            $where['city'] = ['like', '%' . $city . '%'];
        }
        if ($desc) {
            switch ((int) $desc) {
            case 1:
                if ($keyword) {
                    $where['name'] = ['like', '%' . $keyword . '%'];
                }
                $data = Db::name('user_claim_address')
                    ->where($where)
                    ->field('id,name,address,longitude,latitude,city,image_3 image,collect')
                    ->limit(($page - 1) * $pagesize, $pagesize)
                    ->order('sign desc,collect desc')
                    ->select();
                break;
            case 2:
                if ($keyword) {
                    $where['name'] = ['like', '%' . $keyword . '%'];
                }
                $flags = Db::name('flags')->where(['address_id' => ['<>', 0]])->whereTime('create_time', 'week')->group('address_id')->field('address_id, count(address_id) count')->order('count desc')->select();
                if (sizeof($flags)) {
                    $where['id'] = ['in', $flags];
                    $flags       = implode(',', array_column($flags, 'address_id'));
                    $data        = Db::name('user_claim_address')
                        ->where($where)
                        ->field('id,name,address,longitude,latitude,city,image_3 image,collect')
                        ->limit(($page - 1) * $pagesize, $pagesize)
                        ->orderRaw("field(id,$flags)")
                        ->select();
                }
                break;
            case 3:
                if ($keyword) {
                    $where['name'] = ['like', '%' . $keyword . '%'];
                }
                $flags = Db::name('flags')->where(['address_id' => ['<>', 0]])->whereTime('create_time', 'today')->group('address_id')->field('address_id, count(address_id) count')->order('count desc')->select();
                if (sizeof($flags)) {
                    $where['id'] = ['in', $flags];
                    $flags       = implode(',', array_column($flags, 'address_id'));
                    $data        = Db::name('user_claim_address')
                        ->where($where)
                        ->field('id,name,address,longitude,latitude,city,image_3 image,collect')
                        ->limit(($page - 1) * $pagesize, $pagesize)
                        ->orderRaw("field(id,$flags)")
                        ->select();
                }
                break;
            case 4:
                if ($keyword) {
                    $where['name'] = ['like', '%' . $keyword . '%'];
                }
                $addpackets = Db::name('user_address_red_packet')->where(['status' => 0, 'paystate' => 1, 'stock' => ['>', 0]])->group('address_id')->field('address_id, sum(value) val')->order('val desc')->select();
                if (sizeof($addpackets)) {
                    $flags       = implode(',', array_column($addpackets, 'address_id'));
                    $where['id'] = ['in', $flags];
                    $data        = Db::name('user_claim_address')
                        ->where($where)
                        ->field('id,name,address,longitude,latitude,city,image_3 image,collect')
                        ->limit(($page - 1) * $pagesize, $pagesize)
                        ->orderRaw("field(id,$flags)")
                        ->select();
                }
                break;

            default:
                break;
            }
        } else {
            if ($flagcate) {
                $flagcateAddress = Db::name('category_of_flag')->where(['id' => $flagcate, 'require_address' => 1])->cache(60)->value('hot_address_ids');
                if ($flagcateAddress) {
                    $where['id'] = ['in', $flagcateAddress];
                }
            }
            if ($keyword) {
                $where['name'] = ['like', '%' . $keyword . '%'];
            }
            $data = Db::name('user_claim_address')
                ->where($where)
                ->field('id,name,address,longitude,latitude,city,image_3 image,collect')
                ->limit(($page - 1) * $pagesize, $pagesize)
                ->order('sign desc,collect desc')
                ->select();
        }
        $packets      = Db::name('user_address_red_packet')->where(['status' => 0, 'paystate' => 1, 'stock' => ['>', 0], 'address_id' => ['in', array_column($data, 'id')]])->cache(60)->field('address_id,type,price,value')->select();
        $packetsGroup = [];
        foreach ($packets as $key => $value) {
            if (!isset($packetsGroup[$value['address_id']])) {
                $packetsGroup[$value['address_id']] = [];
            }
            $packetsGroup[$value['address_id']][] = $value;
        }
        foreach ($data as $key => $value) {
            $data[$key]['sign_today'] = Db::name('flags')->where(['address_id' => $value['id']])->whereTime('create_time', 'today')->cache(60)->count();
            $data[$key]['sign_week']  = Db::name('flags')->where(['address_id' => $value['id']])->whereTime('create_time', 'week')->cache(60)->count();
            $data[$key]['redpackets'] = $packetsGroup[$value['id']] ?? [];
        }
        return $this->pass($data);
    }
}